package sax;

import java.sql.SQLException;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public class SAXHandler extends DefaultHandler {


	private MySqlWorker worker;

	private boolean processingPeople;

	private StringBuffer strbf = new StringBuffer();

	private ArrayList<String> values;

	private int index = 0;

	private boolean processingTrips;

	private boolean processingCarshop;

	public SAXHandler(MySqlWorker worker) {
		this.worker = worker;
		values = new ArrayList<String>(4);
	}

	public void endPrefixMapping(String prefix) {
	}

	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) {
		if ("people".compareToIgnoreCase(qName) == 0) {
			processingPeople = true;
		} else if ("trips".compareToIgnoreCase(qName) == 0) {
			processingTrips = true;
		} else if ("carshop".compareToIgnoreCase(qName) == 0) {
			processingCarshop = true;
		}
	}

	public void endElement(String namespaceURI, String localName, String qName) {

		if ("people".compareToIgnoreCase(qName) == 0) {
			processingPeople = false;
			index = 0;
		} else if ("trips".compareToIgnoreCase(qName) == 0) {
			processingTrips = false;
			index = 0;
		} else if ("carshop".compareToIgnoreCase(qName) == 0) {

			processingCarshop = false;
			index = 0;

		}

	}

	public void characters(char[] chars, int start, int length) {

		for (int i = start; i < start + length; i++) {
			strbf.append(chars[i]);
		}

		String result = strbf.toString().trim();

		if ("".compareTo(result) != 0) {
			values.add(result);
			strbf.delete(0, strbf.length());
			index++;

		} else {
			if (index != 0) {
				index = 0;
				try {
					if (processingPeople) {
						worker.addToPeople(values);
						values.removeAll(values);
					} else if (processingTrips) {
						worker.addToTrips(values);
						values.removeAll(values);
					} else if (processingCarshop) {
						worker.addToCarshop(values);
						values.removeAll(values);
					}
				} catch (SQLException e) {
					// logger.error(e);
				}
			}
		}

	}
}
